import java.net.*;
import java.io.*;

class SimpleTcpClient {
    DataInputStream dis;
    DataOutputStream dos;
	BufferedReader mIn = new BufferedReader(new InputStreamReader(System.in));

	void work() throws Exception {
		System.out.println("client started.");
        
		Socket s = new Socket("127.0.0.1", 5432);
		InputStream sIn = s.getInputStream();
		dis = new DataInputStream(sIn);
        OutputStream sOut = s.getOutputStream();
		dos = new DataOutputStream(sOut);

        String prompt = """
			[q]uit
			[l]ist all records
			[a]dd a new record
			[d]elete an existed record
			""";

		boolean loop = true;
		while (loop) {
			System.out.println(prompt);
			System.out.print("please input an action: ");
			String choice = mIn.readLine();
			
			switch (choice) {
				case "q":
					quit();
					loop = false;
					break;
				case "l": // list
					list();
					break;
				case "a": // add
					add();
					break;
				case "d": // delete
					delete();
					break;
				}
		
		}

		s.close();

	}

	void quit() throws IOException {
		dos.writeUTF("quit");	
	}
	
	void add() throws IOException {
		System.out.print("name: ");
		String name = mIn.readLine();
		System.out.print("number: ");
		String number = mIn.readLine();
		dos.writeUTF("add");	
        dos.writeUTF(name);
        dos.writeUTF(number);
	}

	void list() throws Exception {
		dos.writeUTF("list");
        int n = dis.readInt();
        for (int i = 0; i < n; i++) {
            String name = dis.readUTF();
            String number = dis.readUTF();
			System.out.println(name);
			System.out.println(number);
			System.out.println("--------------------------------------");
        }
	}	

	void delete() throws Exception {
		System.out.println("name to delete: ");
		String name = mIn.readLine();
		dos.writeUTF("delete");	
        dos.writeUTF(name);
	}

	public static void main(String[] args) throws Exception {
		// controller
		SimpleTcpClient m = new SimpleTcpClient();
		m.work();
	}
    
}
